package com.transaction.manage.util;

import com.transaction.manage.model.dto.FlowInfo;
import com.transaction.manage.model.vo.HandleVo;
import com.transaction.manage.service.dayEnd.HandleDataService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

@Component
public class MultiThreadedUtil {


    private static Logger LOGGER = LoggerFactory.getLogger(MultiThreadedUtil.class);

    @Autowired
    private HandleDataService handleDataServiceBean;
    private static HandleDataService handleDataService;

    //初始化注入bean
    @PostConstruct
    public void init(){
        handleDataService = handleDataServiceBean;
    }

    /**
     * 多线程处理日终日期数据
     * @param flowInfoList 流程信息
     * @param channelCodes 渠道编码集合
     * @param handleDate 处理日期
     * @param flowCode 流程编码
     * @return
     */
    public static List<HandleVo> multiHandleDate(List<FlowInfo> flowInfoList, List<String> channelCodes,
                                                 String handleDate,String flowCode){

        if(CollectionUtils.isEmpty(flowInfoList) || CollectionUtils.isEmpty(channelCodes)
                || StringUtils.isEmpty(handleDate) || StringUtils.isEmpty(flowCode)){
            throw new RuntimeException("请确保流程信息/渠道信息/处理日期/处理流程/参数正常,在调用批量处理方法。");
        }

        List<HandleVo> retList = new ArrayList<>();

        int taskSize = 2;
        // 创建一个线程池
        ExecutorService pool = Executors.newFixedThreadPool(taskSize);
        // 创建多个有返回值的任务
        List<Future> list = new ArrayList<Future>();

        channelCodes.forEach(channelCode ->{
            Callable c = new Callable() {
                @Override
                public Object call(){
                    return handleDataService.handleData(flowInfoList,channelCode,handleDate,flowCode);
                }
            };
            // 执行任务并获取Future对象
            Future f = pool.submit(c);
            list.add(f);
        });
        LOGGER.info("关闭线程池");
        pool.shutdown();

        LOGGER.info("获得处理结果");
        // 获取所有并发任务的运行结果
        for (Future f : list) {
            // 从Future对象上获取任务的返回值，错误的信息返回
            HandleVo retVo = null;
            try {
                retVo = (HandleVo)f.get();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            if(retVo != null && retVo.getRetCode() != null && !"0000".equals(retVo.getRetCode())){
                retList.add(retVo);
            }
        }

        return retList;
    }
}
